package xcmg.device.service.purchase;

import com.github.pagehelper.PageInfo;
import yb.ecp.fast.infra.util.PageHelperPlus;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import xcmg.device.dao.entity.company.CompanySupplierDO;
import xcmg.device.dao.entity.purchase.LinkPurchaseMaterials;
import xcmg.device.dao.entity.purchase.PurchaseInboundDetailDO;
import xcmg.device.dao.entity.purchase.PurchaseInboundDetailDev;
import xcmg.device.dao.entity.purchase.PurchaseInboundDetailExtend;
import xcmg.device.dao.entity.purchase.PurchaseInvoiceApply;
import xcmg.device.dao.entity.purchase.PurchasePriceDO;
import xcmg.device.dao.entity.purchase.PurchaseRequestDO;
import xcmg.device.dao.entity.purchase.PurchaseRequestDetailDO;
import xcmg.device.dao.entity.purchase.PurchaseReturnOutDetail;
import xcmg.device.dao.entity.purchase.PurchaseReturnOutDetailExt;
import xcmg.device.dao.entity.purchaseInvoice.ReqApplyExamine;
import xcmg.device.dao.entity.purchaseInvoice.ReqMateriels;
import xcmg.device.dao.entity.purchaseInvoice.ReqPurchaseInvoiceApply;
import xcmg.device.dao.entity.purchaseInvoice.ReqPurchaseInvoiceCreate;
import xcmg.device.dao.entity.purchaseInvoice.ReqPurchaseInvoiceExportParam;
import xcmg.device.dao.entity.purchaseInvoice.ReqPurchaseInvoiceList;
import xcmg.device.dao.entity.purchaseInvoice.ReqPurchaseInvoiceUpdate;
import xcmg.device.dao.entity.purchaseInvoice.ResInvoiceApply;
import xcmg.device.dao.entity.purchaseInvoice.ResInvoiceApplyDetail;
import xcmg.device.dao.entity.purchaseInvoice.ResMaterials;
import xcmg.device.dao.entity.purchaseInvoice.ResMaterialsInApply;
import xcmg.device.dao.entity.purchaseInvoice.ResPurchaseInvoiceExport;
import xcmg.device.dao.entity.purchaseInvoice.ResPurchaseInvoiceList;
import xcmg.device.dao.mapper.CompanyInfoMapper;
import xcmg.device.dao.mapper.CompanySupplierMapper;
import xcmg.device.dao.mapper.LinkPurchaseMaterialsMapper;
import xcmg.device.dao.mapper.PurchaseInboundDetailDevMapper;
import xcmg.device.dao.mapper.PurchaseInboundDetailExtendMapper;
import xcmg.device.dao.mapper.PurchaseInboundDetailMapper;
import xcmg.device.dao.mapper.PurchaseInvoiceApplyMapper;
import xcmg.device.dao.mapper.PurchasePriceMapper;
import xcmg.device.dao.mapper.PurchaseRequestDetailMapper;
import xcmg.device.dao.mapper.PurchaseRequestMapper;
import xcmg.device.dao.mapper.PurchaseReturnOutDetailExtMapper;
import xcmg.device.dao.mapper.PurchaseReturnOutDetailMapper;
import xcmg.device.infra.DateUtil;
import xcmg.device.infra.ErrorCode;
import xcmg.device.infra.ExportUtil;
import xcmg.device.infra.enums.BillDesc;
import xcmg.device.service.GenDocumentService;
import xcmg.device.util.CodeSalesInvoiceApply;
import xcmg.device.util.CompanyUtil;
import xcmg.device.util.DecimalUtil;
import xcmg.device.util.ToolRandom;
import xcmg.device.util.ToolTime;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@Service
public class PurchaseInvoiceApplyService {
    private Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private PurchaseInvoiceApplyMapper purchaseInvoiceApplyMapper;
    @Autowired
    private PurchaseInboundDetailExtendMapper purchaseInboundDetailExtendMapper;
    @Autowired
    private PurchaseInboundDetailDevMapper purchaseInboundDetailMapper;
    @Autowired
    private LinkPurchaseMaterialsMapper linkPurchaseMaterialsMapper;
    @Autowired
    private GenDocumentService genDocumentService;
    @Autowired
    private CompanySupplierMapper companySupplierMapper;
    @Autowired
    private PurchaseReturnOutDetailMapper purchaseReturnOutDetailMapper;
    @Autowired
    private PurchaseReturnOutDetailExtMapper purchaseReturnOutDetailExtMapper;
    @Autowired
    private PurchasePriceMapper purchasePriceMapper;
    @Autowired
    private PurchaseRequestMapper purchaseRequestMapper;
    @Autowired
    private PurchaseRequestDetailMapper purchaseRequestDetailMapper;
    @Autowired
    private HttpServletResponse response;
    @Autowired
    private PurchaseInboundDetailMapper inboundDetailMapper;
    @Autowired
    private CompanyInfoMapper companyInfoMapper;

    /**
     * getList
     *
     * @param reqPurchaseInvoiceList
     * @param pageNum
     * @param pageSize
     * @return
     * @return PageInfo<ResPurchaseInvoiceList> 返回类型
     * @description <采购开票列表>
     * @author guoxin
     * @version V1.0
     * @date 2019年9月24日
     * @email guoxin@redoornetwork.com
     */
    public PageInfo<ResPurchaseInvoiceList> getList(ReqPurchaseInvoiceList reqPurchaseInvoiceList, String orgId,
                                                    Integer pageNum, Integer pageSize) {
        PageHelperPlus.startPage(pageNum == null ? 1 : pageNum, pageSize == null ? 10 : pageSize);
        List<ResPurchaseInvoiceList> list = purchaseInvoiceApplyMapper.purchaseInvoiceList(reqPurchaseInvoiceList,
                orgId);


        list.forEach(p -> p.setInvoicePrice(p.getInvoicePrice().divide(new BigDecimal(100), 2, RoundingMode.HALF_DOWN)));
        PageInfo<ResPurchaseInvoiceList> page = new PageInfo<>(list);
        return page;
    }

    private List<ResInvoiceApply> applyList(ReqPurchaseInvoiceApply reqPurchaseInvoiceApply, String orgId) {
        List<ResInvoiceApply> list = new ArrayList<>();
        if (CodeSalesInvoiceApply.TYPE.ENTER.equals(reqPurchaseInvoiceApply.getType())) {
            list = purchaseInvoiceApplyMapper.getApplyListInbound(reqPurchaseInvoiceApply, orgId);
            if (list != null && list.size() > 0) {
                for (ResInvoiceApply resInvoiceApply : list) {
                    resInvoiceApply.setType(CodeSalesInvoiceApply.TYPE.ENTER);
                }
            }
        }
        if (CodeSalesInvoiceApply.TYPE.OUT.equals(reqPurchaseInvoiceApply.getType())) {
            list = purchaseInvoiceApplyMapper.getApplyListOut(reqPurchaseInvoiceApply, orgId);
            if (list != null && list.size() > 0) {
                for (ResInvoiceApply resInvoiceApply : list) {
                    resInvoiceApply.setType(CodeSalesInvoiceApply.TYPE.OUT);
                    resInvoiceApply.setPrice(DecimalUtil.divideHundred(resInvoiceApply.getPrice()));
                }
            }
        }
        if (StringUtils.isBlank(reqPurchaseInvoiceApply.getType())) {
            list = purchaseInvoiceApplyMapper.getInAndOutApplyList(reqPurchaseInvoiceApply, orgId);
            if (list != null && list.size() > 0) {
                for (ResInvoiceApply resInvoiceApply : list) {
                    //出库的 数据库价格数据做了乘以100操作，入库没有。所以出库的数据要还原
                    if ("1".equals(resInvoiceApply.getType())) {
                        resInvoiceApply.setPrice(DecimalUtil.divideHundred(resInvoiceApply.getPrice()));
                    }
                }
            }


        }
        return list;
    }

    /**
     * getApplyList
     *
     * @param reqPurchaseInvoiceApply
     * @param pageNum
     * @param pageSize
     * @return
     * @return PageInfo<ResInvoiceApply> 返回类型
     * @description <获取可开票零件列表>
     * @author guoxin
     * @version V1.0
     * @date 2019年9月26日
     * @email guoxin@redoornetwork.com
     */
    public PageInfo<ResInvoiceApply> getApplyList(ReqPurchaseInvoiceApply reqPurchaseInvoiceApply, String orgId,
                                                  Integer pageNum, Integer pageSize) {
        List<ResInvoiceApply> list = new ArrayList<>();
        PageHelperPlus.startPage(pageNum == null ? 1 : pageNum, pageSize == null ? 10 : pageSize);
        list = applyList(reqPurchaseInvoiceApply, orgId);
        PageInfo<ResInvoiceApply> page = new PageInfo<>(list);
        return page;
    }

    /**
     * addPurchaseInvoiceApply
     *
     * @param reqPurchaseInvoiceCreate
     * @param orgId
     * @return
     * @return ErrorCode 返回类型
     * @throws Exception
     * @description <采购开票新增>
     * @author guoxin
     * @version V1.0
     * @date 2019年9月27日
     * @email guoxin@redoornetwork.com
     */
    @Transactional(rollbackFor = Exception.class)
    public ErrorCode addPurchaseInvoiceApply(ReqPurchaseInvoiceCreate reqPurchaseInvoiceCreate, String orgId,
                                             String userId, String userName) throws Exception {
        if (reqPurchaseInvoiceCreate.getMateriels().size() == 0 || reqPurchaseInvoiceCreate.getMateriels() == null) {
            logger.warn("零件列表为空，校验失败");
            return ErrorCode.MaterialListNotExists;
        }
        CompanySupplierDO supplier = companySupplierMapper.itemBySupplierOrgId(orgId,
                reqPurchaseInvoiceCreate.getSupplierOrgId());
        if (supplier == null) {
            logger.warn("未查询到供应商信息，供应商id有误");
            return ErrorCode.SuppierIDNotExist;
        }
        if (StringUtils.isNotBlank(reqPurchaseInvoiceCreate.getRemark())) {
            if (reqPurchaseInvoiceCreate.getRemark().length() > 100) {
                logger.warn("备注过长，校验失败");
                return ErrorCode.RemarkTooLong;
            }
        }
        PurchaseInvoiceApply apply = new PurchaseInvoiceApply();
        String ID = ToolTime.getNowStringByAllTime() + ToolRandom.getStringByLen(6).toUpperCase();
        BigDecimal totalPrice = BigDecimal.ZERO;
        BigDecimal totalNum = BigDecimal.ZERO;
        logger.info("开始校验零件列表合法性");
        for (ReqMateriels reqMateriels : reqPurchaseInvoiceCreate.getMateriels()) {
            totalNum = totalNum.add(reqMateriels.getInvoiceNum());
            updateExtendTable(reqMateriels.getID(), reqMateriels.getOrderType());
            if (!whetherEnough(reqMateriels.getID(), reqMateriels.getOrderType(), reqMateriels.getInvoiceNum())) {
                logger.warn("id={}的零件可开票数量不足，校验失败", reqMateriels.getID());
                return ErrorCode.InvoiceNotEnough;
            }
        }
        if (totalNum.compareTo(new BigDecimal(0)) == 0) {
            logger.warn("零件列表数量不能全为0");
            return ErrorCode.InvoiceNumError;
        }
        logger.info("校验完成，零件列表通过校验");
        totalNum = BigDecimal.ZERO;
        for (ReqMateriels reqMateriels : reqPurchaseInvoiceCreate.getMateriels()) {
            if (CodeSalesInvoiceApply.TYPE.ENTER.equals(reqMateriels.getOrderType())) {
                BigDecimal materielPrice = purchaseInvoiceApplyMapper.materielPriceEnter(reqMateriels.getID());
                totalPrice = totalPrice.add(materielPrice.multiply(reqMateriels.getInvoiceNum()));
                String LinkID = ToolTime.getNowStringByAllTime() + ToolRandom.getStringByLen(6).toUpperCase();
                LinkPurchaseMaterials linkPurchaseMaterials = new LinkPurchaseMaterials();
                linkPurchaseMaterials.setId(LinkID);
                linkPurchaseMaterials.setPurchaseId(ID);
                linkPurchaseMaterials.setDetailId(reqMateriels.getID());
                linkPurchaseMaterials.setOrderType(Long.valueOf(CodeSalesInvoiceApply.TYPE.ENTER));
                linkPurchaseMaterials.setInvoiceNum(reqMateriels.getInvoiceNum());
                logger.info("开票零件对象构建完成,开票id={},零件id={},本次开票数量num={} ", ID, reqMateriels.getID(),
                        reqMateriels.getInvoiceNum());
                linkPurchaseMaterialsMapper.insert(linkPurchaseMaterials);
                logger.info("开票零件入库完成");
                logger.info("开始更新零件已开票数量");
                PurchaseInboundDetailExtend extend = new PurchaseInboundDetailExtend();
                extend.setId(reqMateriels.getID());
                updateExtendTable(reqMateriels.getID(), reqMateriels.getOrderType());
                extend = purchaseInboundDetailExtendMapper.selectByKey(extend);
                extend.setInvoicesIssued(extend.getInvoicesIssued().add(reqMateriels.getInvoiceNum()));
                purchaseInboundDetailExtendMapper.update(extend);
                logger.info("零件开票数量更新完成");
            }
            if (CodeSalesInvoiceApply.TYPE.OUT.equals(reqMateriels.getOrderType())) {
                BigDecimal materielPrice = purchaseInvoiceApplyMapper.materielPriceOut(reqMateriels.getID());
                totalPrice = totalPrice.subtract(materielPrice.multiply(reqMateriels.getInvoiceNum()));
                String LinkID = ToolTime.getNowStringByAllTime() + ToolRandom.getStringByLen(6).toUpperCase();
                LinkPurchaseMaterials linkPurchaseMaterials = new LinkPurchaseMaterials();
                linkPurchaseMaterials.setId(LinkID);
                linkPurchaseMaterials.setPurchaseId(ID);
                linkPurchaseMaterials.setDetailId(reqMateriels.getID());
                linkPurchaseMaterials.setOrderType(Long.valueOf(CodeSalesInvoiceApply.TYPE.OUT));
                linkPurchaseMaterials.setInvoiceNum(reqMateriels.getInvoiceNum());
                logger.info("开票零件对象构建完成,开票id={},零件id={},本次开票数量num={} ", ID, reqMateriels.getID(),
                        reqMateriels.getInvoiceNum());
                linkPurchaseMaterialsMapper.insert(linkPurchaseMaterials);
                logger.info("开票零件入库完成");
                logger.info("开始更新零件已开票数量");
                PurchaseReturnOutDetailExt extend = new PurchaseReturnOutDetailExt();
                extend.setId(reqMateriels.getID());
                updateExtendTable(reqMateriels.getID(), reqMateriels.getOrderType());
                extend = purchaseReturnOutDetailExtMapper.selectByKey(extend);
                extend.setInvoicesIssued(extend.getInvoicesIssued().add(reqMateriels.getInvoiceNum()));
                purchaseReturnOutDetailExtMapper.update(extend);
                logger.info("零件开票数量更新完成");
            }
        }
        apply.setId(ID);
        apply.setOrgId(orgId);
        apply.setSupplierOrgid(reqPurchaseInvoiceCreate.getSupplierOrgId());
        apply.setSupplierName(supplier.getCompanyName());
        apply.setPurchaseInvoiceOrder(genDocumentService.genDocumentNo(BillDesc.PurchaseInvoice, orgId));
        apply.setInvoicePrice(totalPrice);
        apply.setRemark(reqPurchaseInvoiceCreate.getRemark());
        apply.setIsDel(new BigDecimal(CodeSalesInvoiceApply.IS_DEL.NO));
        apply.setApplyTime(ToolTime.getNowDate());
        apply.setApplyPrice(BigDecimal.ZERO);
        apply.setApplyId(userId);
        apply.setApplyName(userName);
        apply.setStatus(new BigDecimal(CodeSalesInvoiceApply.STATUS.WAIT));
        purchaseInvoiceApplyMapper.insert(apply);
        logger.info("采购开票申请单入库成功");
        return ErrorCode.Success;
    }

    private boolean whetherEnough(String id, String orderType, BigDecimal invoiceNum) {
        logger.info("开始比对零件可开票数量是否充足，id={}，invoceNum={}", id, invoiceNum);
        if (CodeSalesInvoiceApply.TYPE.ENTER.equals(orderType)) {
            PurchaseInboundDetailDev detail = new PurchaseInboundDetailDev();
            detail.setId(id);
            detail = purchaseInboundDetailMapper.selectByKey(detail);
            if (detail != null) {
                PurchaseInboundDetailExtend extend = new PurchaseInboundDetailExtend();
                extend.setId(id);
                extend = purchaseInboundDetailExtendMapper.selectByKey(extend);
                if (extend != null) {
                    BigDecimal already = extend.getInvoicesIssued() == null ? BigDecimal.ZERO
                            : extend.getInvoicesIssued();
                    if (new BigDecimal(detail.getRealAmount()).subtract(already).compareTo(invoiceNum) != -1) {
                        return true;
                    }
                }
            }
        }
        if (CodeSalesInvoiceApply.TYPE.OUT.equals(orderType)) {
            PurchaseReturnOutDetail detail = new PurchaseReturnOutDetail();
            detail.setId(id);
            detail = purchaseReturnOutDetailMapper.selectByKey(detail);
            if (detail != null) {
                PurchaseReturnOutDetailExt extend = new PurchaseReturnOutDetailExt();
                extend.setId(id);
                extend = purchaseReturnOutDetailExtMapper.selectByKey(extend);
                if (extend != null) {
                    BigDecimal already = extend.getInvoicesIssued() == null ? BigDecimal.ZERO
                            : extend.getInvoicesIssued();
                    if (detail.getRealOutQty().subtract(already).compareTo(invoiceNum) != -1) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    /**
     * updatePurchaseInvoiceApply
     *
     * @param reqPurchaseInvoiceUpdate
     * @return
     * @return ErrorCode 返回类型
     * @description <采购开票申请更新>
     * @author guoxin
     * @version V1.0
     * @date 2019年10月2日
     * @email guoxin@redoornetwork.com
     */
    @Transactional(rollbackFor = Exception.class)
    public ErrorCode updatePurchaseInvoiceApply(ReqPurchaseInvoiceUpdate reqPurchaseInvoiceUpdate) {
        logger.info("更新采购开票申请单，开始,reqPurchaseInvoiceUpdate=" + reqPurchaseInvoiceUpdate);
        PurchaseInvoiceApply purchaseInvoiceApply = new PurchaseInvoiceApply();
        purchaseInvoiceApply.setId(reqPurchaseInvoiceUpdate.getId());
        purchaseInvoiceApply.setIsDel(new BigDecimal(CodeSalesInvoiceApply.IS_DEL.NO));
        List<PurchaseInvoiceApply> list = purchaseInvoiceApplyMapper.selectListByExact(purchaseInvoiceApply);
        if (list == null || list.size() == 0) {
            logger.warn("更新采购开票申请单失败，id不能为空");
            return ErrorCode.InvoiceApplyNotExist;
        }
        if (CodeSalesInvoiceApply.STATUS.PASS.equals(list.get(0).getStatus().toString())) {
            logger.warn("该采购开票申请单已通过审批，无法编辑");
            return ErrorCode.CannotEdit;
        }
        List<ResMaterials> materielList = materielsList(reqPurchaseInvoiceUpdate.getId());
        if (materielList == null || materielList.size() == 0) {
            logger.warn("更新采购开票申请单失败，查询到该id零件为空");
            return ErrorCode.MaterielNotExist;
        }
        List<ReqMateriels> materielList2 = reqPurchaseInvoiceUpdate.getMateriels();
        if (materielList2 == null || materielList2.size() == 0) {
            logger.warn("更新采购开票申请单失败,至少选择一种零件");
            return ErrorCode.MaterialListNotExists;
        }
        for (ReqMateriels reqMateriels : reqPurchaseInvoiceUpdate.getMateriels()) {
            if (reqMateriels.getInvoiceNum().compareTo(BigDecimal.ZERO) != 1) {
                logger.warn("更新采购开票申请单失败,有零件开票数量错误或为零");
                return ErrorCode.InvoiceNumNull;
            }
        }
        List<String> oldList = new ArrayList<>();
        List<String> oldOutList = new ArrayList<>();
        for (ResMaterials oldMateriel : materielList) {
            if (CodeSalesInvoiceApply.TYPE.ENTER.equals(oldMateriel.getType())) {
                oldList.add(oldMateriel.getMaterielId());
            }
            if (CodeSalesInvoiceApply.TYPE.OUT.equals(oldMateriel.getType())) {
                oldOutList.add(oldMateriel.getMaterielId());
            }
        }
        List<String> newList = new ArrayList<>();
        List<String> newOutList = new ArrayList<>();
        BigDecimal total = new BigDecimal("0");
        for (ReqMateriels newMateriel : reqPurchaseInvoiceUpdate.getMateriels()) {
            if (CodeSalesInvoiceApply.TYPE.ENTER.equals(newMateriel.getOrderType())) {
                newList.add(newMateriel.getID());
                PurchaseInboundDetailDev detail = new PurchaseInboundDetailDev();
                detail.setId(newMateriel.getID());
                detail = purchaseInboundDetailMapper.selectByKey(detail);
                total = total.add(DecimalUtil.multiplyHundred(detail.getPrice()).multiply(newMateriel.getInvoiceNum()));
            }
            if (CodeSalesInvoiceApply.TYPE.OUT.equals(newMateriel.getOrderType())) {
                newOutList.add(newMateriel.getID());
                PurchaseReturnOutDetail detail = new PurchaseReturnOutDetail();
                detail.setId(newMateriel.getID());
                detail = purchaseReturnOutDetailMapper.selectByKey(detail);
                total = total.subtract(detail.getPrice().multiply(newMateriel.getInvoiceNum()));
            }
        }
        logger.info("计算出编辑后该开票申请单id={}的开票总金额={}", reqPurchaseInvoiceUpdate.getId(), total);
        oldList.removeAll(newList);
        for (String id : oldList) {
            LinkPurchaseMaterials link = new LinkPurchaseMaterials();
            link.setDetailId(id);
            link.setOrderType(Long.valueOf(CodeSalesInvoiceApply.TYPE.ENTER));
            link.setPurchaseId(reqPurchaseInvoiceUpdate.getId());
            logger.info("开始查询采购开票申请关联零件id={}的信息", id);
            List<LinkPurchaseMaterials> linkList = linkPurchaseMaterialsMapper.selectListByExact(link);
            if (linkList != null && linkList.size() != 0) {
                link = linkList.get(0);
                logger.info("查询完成，link=" + link);
                BigDecimal invoiceNum = link.getInvoiceNum();
                logger.info("开始归还零件可开票库存，归还数量={},归还零件id={}", invoiceNum, link.getDetailId());
                logger.info("开始查询零件id={}", link.getDetailId());
                PurchaseInboundDetailExtend extend = new PurchaseInboundDetailExtend();
                extend.setId(link.getDetailId());
                extend = purchaseInboundDetailExtendMapper.selectByKey(extend);
                logger.info("查询到零件=" + extend);
                BigDecimal newInvoiceNum = extend.getInvoicesIssued().subtract(invoiceNum);
                extend.setInvoicesIssued(newInvoiceNum);
                purchaseInboundDetailExtendMapper.update(extend);
                logger.info("零件归还完成，归还零件id={}，归还后数量={}", link.getDetailId(), newInvoiceNum);
                logger.info("开始删除采购开票申请关联零件id:" + id);
                linkPurchaseMaterialsMapper.delete(link);
                logger.info("采购开票申请关联零件id={}删除完成,", id);
            } else {
                logger.warn("未查询到采购开票申请关联零件id={}的信息", id);
                break;
            }
        }
        for (String id : newList) {
            LinkPurchaseMaterials link = new LinkPurchaseMaterials();
            link.setDetailId(id);
            link.setOrderType(Long.valueOf(CodeSalesInvoiceApply.TYPE.ENTER));
            link.setPurchaseId(reqPurchaseInvoiceUpdate.getId());
            logger.info("开始查询采购开票申请关联零件id={}的信息", id);
            List<LinkPurchaseMaterials> linkList = linkPurchaseMaterialsMapper.selectListByExact(link);
            if (linkList != null && linkList.size() != 0) {
                link = linkList.get(0);
                logger.info("查询完成，link=" + link);
                for (ReqMateriels reqMateriels : reqPurchaseInvoiceUpdate.getMateriels()) {
                    if (reqMateriels.getID().equals(link.getDetailId())
                            && CodeSalesInvoiceApply.TYPE.ENTER.equals(reqMateriels.getOrderType())) {
                        logger.info("开始计算开票零件数量变化,零件id=" + reqMateriels.getID());
                        BigDecimal diff = reqMateriels.getInvoiceNum().subtract(link.getInvoiceNum());
                        logger.info("得到差值为={},修改前开票={}张,修改后开票={}张", diff, link.getInvoiceNum(),
                                reqMateriels.getInvoiceNum());
                        logger.info("开始查询原已开票数量");
                        PurchaseInboundDetailExtend extend = new PurchaseInboundDetailExtend();
                        extend.setId(reqMateriels.getID());
                        extend = purchaseInboundDetailExtendMapper.selectByKey(extend);
                        BigDecimal newNum = extend.getInvoicesIssued().add(diff);
                        logger.info("已计算出更新后已开票数量={}", newNum);
                        extend.setInvoicesIssued(newNum);
                        purchaseInboundDetailExtendMapper.update(extend);
                        logger.info("已成功更新可开票数量");
                        logger.info("开始更新link表零件本次开票数量,零件id=" + id);
                        link.setInvoiceNum(reqMateriels.getInvoiceNum());
                        linkPurchaseMaterialsMapper.update(link);
                        break;
                    }
                }

            } else {
                logger.warn("未查询到采购开票申请关联零件id={}的信息", id);
                break;
            }
        }
        oldOutList.removeAll(newOutList);
        for (String id : oldOutList) {
            LinkPurchaseMaterials link = new LinkPurchaseMaterials();
            link.setDetailId(id);
            link.setOrderType(Long.valueOf(CodeSalesInvoiceApply.TYPE.OUT));
            link.setPurchaseId(reqPurchaseInvoiceUpdate.getId());
            logger.info("开始查询采购开票申请关联零件id={}的信息", id);
            List<LinkPurchaseMaterials> linkList = linkPurchaseMaterialsMapper.selectListByExact(link);
            if (linkList != null && linkList.size() != 0) {
                link = linkList.get(0);
                logger.info("查询完成，link=" + link);
                BigDecimal invoiceNum = link.getInvoiceNum();
                logger.info("开始归还零件可开票库存，归还数量={},归还零件id={}", invoiceNum, link.getDetailId());
                logger.info("开始查询零件id={}", link.getDetailId());
                PurchaseReturnOutDetailExt extend = new PurchaseReturnOutDetailExt();
                extend.setId(link.getDetailId());
                extend = purchaseReturnOutDetailExtMapper.selectByKey(extend);
                logger.info("查询到零件=" + extend);
                BigDecimal newInvoiceNum = extend.getInvoicesIssued().subtract(invoiceNum);
                extend.setInvoicesIssued(newInvoiceNum);
                purchaseReturnOutDetailExtMapper.update(extend);
                logger.info("零件归还完成，归还零件id={}，归还后数量={}", link.getDetailId(), newInvoiceNum);
                logger.info("开始删除采购开票申请关联零件id:" + id);
                linkPurchaseMaterialsMapper.delete(link);
                logger.info("采购开票申请关联零件id={}删除完成,", id);
            } else {
                logger.warn("未查询到采购开票申请关联零件id={}的信息", id);
                break;
            }
        }
        for (String id : newOutList) {
            LinkPurchaseMaterials link = new LinkPurchaseMaterials();
            link.setDetailId(id);
            link.setOrderType(Long.valueOf(CodeSalesInvoiceApply.TYPE.OUT));
            link.setPurchaseId(reqPurchaseInvoiceUpdate.getId());
            logger.info("开始查询采购开票申请关联零件id={}的信息", id);
            List<LinkPurchaseMaterials> linkList = linkPurchaseMaterialsMapper.selectListByExact(link);
            if (linkList != null && linkList.size() != 0) {
                link = linkList.get(0);
                logger.info("查询完成，link=" + link);
                for (ReqMateriels reqMateriels : reqPurchaseInvoiceUpdate.getMateriels()) {
                    if (reqMateriels.getID().equals(link.getDetailId())
                            && CodeSalesInvoiceApply.TYPE.OUT.equals(reqMateriels.getOrderType())) {
                        logger.info("开始计算开票零件数量变化,零件id=" + reqMateriels.getID());
                        BigDecimal diff = reqMateriels.getInvoiceNum().subtract(link.getInvoiceNum());
                        logger.info("得到差值为={},修改前开票={}张,修改后开票={}张", diff, link.getInvoiceNum(),
                                reqMateriels.getInvoiceNum());
                        logger.info("开始查询原已开票数量");
                        PurchaseReturnOutDetailExt extend = new PurchaseReturnOutDetailExt();
                        extend.setId(reqMateriels.getID());
                        extend = purchaseReturnOutDetailExtMapper.selectByKey(extend);
                        BigDecimal newNum = extend.getInvoicesIssued().add(diff);
                        logger.info("已计算出更新后已开票数量={}", newNum);
                        extend.setInvoicesIssued(newNum);
                        purchaseReturnOutDetailExtMapper.update(extend);
                        logger.info("已成功更新可开票数量");
                        logger.info("开始更新link表零件本次开票数量,零件id=" + id);
                        link.setInvoiceNum(reqMateriels.getInvoiceNum());
                        linkPurchaseMaterialsMapper.update(link);
                        break;
                    }
                }

            } else {
                logger.warn("未查询到采购开票申请关联零件id={}的信息", id);
                break;
            }
        }
        purchaseInvoiceApply.setRemark(reqPurchaseInvoiceUpdate.getRemark());
        purchaseInvoiceApply.setInvoicePrice(total);
        purchaseInvoiceApply.setStatus(new BigDecimal(CodeSalesInvoiceApply.STATUS.WAIT));
        logger.info("开始更新采购开票申请单");
        purchaseInvoiceApplyMapper.update(purchaseInvoiceApply);
        logger.info("更新采购开票申请单完成,purchaseInvoiceApply=" + purchaseInvoiceApply);
        return ErrorCode.Success;
    }

    /**
     * materialsInApply
     *
     * @description <根据采购开票申请单id查询申请单中零件列表>
     * @param invoiceApplyId
     * @return
     * @return List<ResMaterialsInApply> 返回类型
     * @author guoxin
     * @version V1.0
     * @date 2019年10月2日
     * @email guoxin@redoornetwork.com
     */
    // public PageInfo<ResMaterialsInApply> materialsInApply( String invoiceApplyId,
    // Integer pageNum, Integer pageSize )
    // {
    // PageHelperPlus.startPage( pageNum == null ? 1 : pageNum, pageSize == null ? 10 :
    // pageSize );
    // List<ResMaterialsInApply> list = purchaseInvoiceApplyMapper.materielsInApply(
    // invoiceApplyId );
    // PageInfo<ResMaterialsInApply> page = new PageInfo<>( list );
    // return page;
    // }

    /**
     * examine
     *
     * @param reqApplyExamine
     * @return
     * @return ErrorCode 返回类型
     * @description <采购开票申请审核>
     * @author guoxin
     * @version V1.0
     * @date 2019年10月2日
     * @email guoxin@redoornetwork.com
     */
    @Transactional(rollbackFor = Exception.class)
    public ErrorCode examine(ReqApplyExamine reqApplyExamine, String userName) {
        logger.info("开始查询采购申请单id={}的对象详情", reqApplyExamine.getInvoiceApplyId());
        PurchaseInvoiceApply apply = new PurchaseInvoiceApply();
        apply.setId(reqApplyExamine.getInvoiceApplyId());
        apply.setIsDel(new BigDecimal(CodeSalesInvoiceApply.IS_DEL.NO));
        List<PurchaseInvoiceApply> list = purchaseInvoiceApplyMapper.selectListByExact(apply);
        if (list == null || list.size() == 0) {
            logger.warn("没有查询到采购申请单id={}的对象数据", reqApplyExamine.getInvoiceApplyId());
            return ErrorCode.InvoiceApplyNotExist;
        }
        if (reqApplyExamine.getStatusCode() == null) {
            logger.warn("采购申请单审批状态码为空");
            return ErrorCode.statusCodeError;
        } else {
            apply = list.get(0);
            if (String.valueOf(apply.getStatus()).equals(CodeSalesInvoiceApply.STATUS.PASS)) {
                logger.warn("该采购申请单已通过审批，无需操作");
                return ErrorCode.alreadyPass;
            }
            if (!String.valueOf(reqApplyExamine.getStatusCode()).equals(CodeSalesInvoiceApply.STATUS.PASS)
                    && !String.valueOf(reqApplyExamine.getStatusCode()).equals(CodeSalesInvoiceApply.STATUS.FAIL)) {
                logger.warn("采购申请单审批状态码错误,statusCode={}", reqApplyExamine.getStatusCode());
                return ErrorCode.statusCodeError;
            }
            if (reqApplyExamine.getSuggestion().length() > 100) {
                logger.warn("审批意见不能超过100字");
                return ErrorCode.suggestionTooLong;
            }
            apply.setStatus(new BigDecimal(reqApplyExamine.getStatusCode()));
            apply.setAuditOpinion(reqApplyExamine.getSuggestion());
            apply.setReviewer(userName);
            apply.setReviewTime(ToolTime.getNowDate());
            logger.info("开始更新采购开票申请审批状态,apply={}", apply);
            purchaseInvoiceApplyMapper.update(apply);
            logger.info("更新采购开票申请审批状态成功");
            return ErrorCode.Success;
        }
    }

    /**
     * deletePurchaseInvoiceApply
     *
     * @param invoiceApplyId
     * @return
     * @return ErrorCode 返回类型
     * @description <删除采购开票申请单>
     * @author guoxin
     * @version V1.0
     * @date 2019年10月2日
     * @email guoxin@redoornetwork.com
     */
    @Transactional(rollbackFor = Exception.class)
    public ErrorCode deletePurchaseInvoiceApply(String invoiceApplyId) {
        logger.info("开始删除id={}的采购开票申请单", invoiceApplyId);
        PurchaseInvoiceApply apply = new PurchaseInvoiceApply();
        if (StringUtils.isBlank(invoiceApplyId)) {
            logger.warn("id不能为空");
            return ErrorCode.ApplyIdisEmpty;
        }
        apply.setId(invoiceApplyId);
        apply.setIsDel(new BigDecimal(CodeSalesInvoiceApply.IS_DEL.NO));
        List<PurchaseInvoiceApply> list = purchaseInvoiceApplyMapper.selectListByExact(apply);
        if (list == null || list.size() == 0) {
            logger.warn("没有查询到采购申请单id={}的对象数据", invoiceApplyId);
            return ErrorCode.InvoiceApplyNotExist;
        } else {
            apply = list.get(0);
            if (CodeSalesInvoiceApply.STATUS.PASS.equals(String.valueOf(apply.getStatus()))) {
                logger.warn("该采购开票申请单已通过审核，无法删除");
                return ErrorCode.CannotDeleteCausePassed;
            }
            logger.info("开始归还申请单中零件的可开发票数量");
            List<ResMaterials> materials = purchaseInvoiceApplyMapper.materiels(invoiceApplyId);
            logger.info("该申请单包含的零件list=" + materials);
            if (materials != null && materials.size() > 0) {
                for (ResMaterials resMaterials : materials) {
                    LinkPurchaseMaterials link = new LinkPurchaseMaterials();
                    link.setDetailId(resMaterials.getMaterielId());
                    link.setPurchaseId(invoiceApplyId);
                    List<LinkPurchaseMaterials> links = linkPurchaseMaterialsMapper.selectListByExact(link);
                    if (links != null && links.size() > 0) {
                        link = links.get(0);
                        BigDecimal invoiceNum = link.getInvoiceNum();
                        if (CodeSalesInvoiceApply.TYPE.ENTER.equals(resMaterials.getType())) {
                            PurchaseInboundDetailExtend extend = new PurchaseInboundDetailExtend();
                            extend.setId(resMaterials.getMaterielId());
                            extend = purchaseInboundDetailExtendMapper.selectByKey(extend);
                            extend.setInvoicesIssued(extend.getInvoicesIssued().subtract(invoiceNum));
                            purchaseInboundDetailExtendMapper.update(extend);
                            logger.info("已归还可开发票数量,invoiceNum={}", invoiceNum);
                            logger.info("开始删除id={}的关联信息", link.getId());
                            linkPurchaseMaterialsMapper.delete(link);
                            logger.info("id={}的关联信息删除成功", link.getId());
                        }
                        if (CodeSalesInvoiceApply.TYPE.OUT.equals(resMaterials.getType())) {
                            PurchaseReturnOutDetailExt extend = new PurchaseReturnOutDetailExt();
                            extend.setId(resMaterials.getMaterielId());
                            extend = purchaseReturnOutDetailExtMapper.selectByKey(extend);
                            extend.setInvoicesIssued(extend.getInvoicesIssued().subtract(invoiceNum));
                            purchaseReturnOutDetailExtMapper.update(extend);
                            logger.info("已归还可开发票数量,invoiceNum={}", invoiceNum);
                            logger.info("开始删除id={}的关联信息", link.getId());
                            linkPurchaseMaterialsMapper.delete(link);
                            logger.info("id={}的关联信息删除成功", link.getId());
                        }
                    }
                }
            }
            apply.setIsDel(new BigDecimal(CodeSalesInvoiceApply.IS_DEL.YES));
            logger.info("删除id={}采购开票申请单，开始更新数据库", invoiceApplyId);
            purchaseInvoiceApplyMapper.update(apply);
            logger.info("id={}采购开票申请单删除完成", invoiceApplyId);
            return ErrorCode.Success;
        }
    }

    /**
     * detail
     *
     * @param invoiceApplyId
     * @return
     * @return ResInvoiceApplyDetail 返回类型
     * @description <采购申请单详情>
     * @author guoxin
     * @version V1.0
     * @date 2019年10月3日
     * @email guoxin@redoornetwork.com
     */
    public ResInvoiceApplyDetail detail(String invoiceApplyId) {
        ResInvoiceApplyDetail resInvoiceApplyDetail = new ResInvoiceApplyDetail();
        resInvoiceApplyDetail = purchaseInvoiceApplyMapper.invoiceApplyDetail(invoiceApplyId);
        resInvoiceApplyDetail.setInvoicePrice(DecimalUtil.divideHundred(resInvoiceApplyDetail.getInvoicePrice()));
        List<ResMaterialsInApply> materials = purchaseInvoiceApplyMapper.materielsInApplyEnter(invoiceApplyId);
        List<ResMaterialsInApply> materials2 = purchaseInvoiceApplyMapper.materielsInApplyOut(invoiceApplyId);
        materials2.forEach(p -> p.setPrice(DecimalUtil.divideHundred(p.getPrice())));
        materials.addAll(materials2);
        if (materials != null && materials.size() > 0) {
            resInvoiceApplyDetail.setMaterials(materials);
        }
        return resInvoiceApplyDetail;
    }

    private List<ResMaterials> materielsList(String invoiceApplyId) {
        logger.info("开始查询采购开票申请单零件列表,InvoiceApplyId=" + invoiceApplyId);
        List<ResMaterials> list = purchaseInvoiceApplyMapper.materiels(invoiceApplyId);
        logger.info("查询采购开票申请单零件列表完成，list=" + list);
        return list;
    }

    /**
     * updateExtendTable
     *
     * @param detailId
     * @param orderType
     * @return void 返回类型
     * @description <如果extand表不存在对应主表的数据，则新增一条初始数据>
     * @author guoxin
     * @version V1.0
     * @date 2019年10月31日
     * @email guoxin@redoornetwork.com
     */
    @Transactional(rollbackFor = Exception.class)
    void updateExtendTable(String detailId, String orderType) {
        if (orderType != null && CodeSalesInvoiceApply.TYPE.ENTER.equals(orderType)) {
            PurchaseInboundDetailExtend extend = new PurchaseInboundDetailExtend();
            extend.setId(detailId);
            extend = purchaseInboundDetailExtendMapper.selectByKey(extend);
            if (extend == null) {
                extend = new PurchaseInboundDetailExtend();
                extend.setId(detailId);
                extend.setInvoicesIssued(BigDecimal.ZERO);
                purchaseInboundDetailExtendMapper.insert(extend);
            }
        }
        if (orderType != null && CodeSalesInvoiceApply.TYPE.OUT.equals(orderType)) {
            PurchaseReturnOutDetailExt detail = new PurchaseReturnOutDetailExt();
            detail.setId(detailId);
            detail = purchaseReturnOutDetailExtMapper.selectByKey(detail);
            if (detail == null) {
                detail = new PurchaseReturnOutDetailExt();
                detail.setId(detailId);
                detail.setInvoicesIssued(BigDecimal.ZERO);
                purchaseReturnOutDetailExtMapper.insert(detail);
            }
        }
    }

    public void export(List<String> asList, String orgId) throws Exception {
        List<ResPurchaseInvoiceList> voList = new ArrayList<>();
        for (String id : asList) {
            PurchaseInvoiceApply object = new PurchaseInvoiceApply();
            object.setId(id);
            PurchaseInvoiceApply selectByKey = purchaseInvoiceApplyMapper.selectByKey(object);
            ResPurchaseInvoiceList model = new ResPurchaseInvoiceList();
            BeanUtils.copyProperties(selectByKey, model);
            model.setStatus(selectByKey.getStatus().longValue());
            model.setApplyTime(DateUtil.formatDateTime(selectByKey.getApplyTime()));
            if (model != null) {
                voList.add(model);
            }
        }
        voList.stream().forEach(k -> {
            if (k != null && k.getApplyPrice() != null) {
                k.setApplyPrice(DecimalUtil.divideHundred(k.getApplyPrice()));
            }
            if (k != null && k.getInvoicePrice() != null) {
                k.setInvoicePrice(DecimalUtil.divideHundred(k.getInvoicePrice()));
            }
        });
        invokeExport(voList);

    }

    public void exportAll(ReqPurchaseInvoiceList condition, String orgId) throws Exception {


        List<ResPurchaseInvoiceList> list = purchaseInvoiceApplyMapper.purchaseInvoiceList(condition,
                orgId);
        list.stream().forEach(k -> {
            if (k != null && k.getApplyPrice() != null) {
                k.setApplyPrice(DecimalUtil.divideHundred(k.getApplyPrice()));
            }
            if (k != null && k.getInvoicePrice() != null) {
                k.setInvoicePrice(DecimalUtil.divideHundred(k.getInvoicePrice()));
            }
        });
        invokeExport(list);

    }

    public void exportDetail(List<String> ids, String orgId) throws Exception {
        ReqPurchaseInvoiceExportParam condition = new ReqPurchaseInvoiceExportParam();
        condition.setIds(ids);
        List<ResPurchaseInvoiceExport> resPurchaseInvoiceExports = purchaseInvoiceApplyMapper.exportDetailAll(condition, orgId);
        invokeExportDetail(resPurchaseInvoiceExports);

    }

    /**
     * @Des 采购开票导出全部（导出的为明细）
     * @Date 2020/11/18 14:23
     * @Author wangzhaoyu
     * @Param [condition, orgId]
     * @Return void
     */
    public void exportDetailAll(ReqPurchaseInvoiceExportParam condition, String orgId) throws Exception {
        List<ResPurchaseInvoiceExport> resPurchaseInvoiceExports = purchaseInvoiceApplyMapper.exportDetailAll(condition, orgId);
        invokeExportDetail(resPurchaseInvoiceExports);
    }

    private void invokeExportDetail(List<ResPurchaseInvoiceExport> resPurchaseInvoiceExports) throws Exception {
        String title = "采购开票数据导出";
        //申请单号，供应商代码，供应商名称，收货单号，采购单号，业务单号，零件编码，零件名称，单位，单价，数量，金额，发票号
        String[] rowsName = new String[]{"序号", "开票申请单号", "供应商代码", "供应商名称", "采购单号", "业务单号", "零件编码", "零件名称", "单位"
                , "单价", "数量", "金额", "备注"};
        List<Object[]> dataList = new ArrayList<Object[]>();
        Object[] objs = null;
        for (int i = 0; i < resPurchaseInvoiceExports.size(); i++) {
            ResPurchaseInvoiceExport e = resPurchaseInvoiceExports.get(i);
            objs = new Object[rowsName.length];
            objs[0] = i + 1;
            objs[1] = e.getPurchaseInvoiceOrder();
            objs[2] = e.getSupplierOrgId();
            objs[3] = e.getSupplierName();
            objs[4] = e.getPurchaseRequestOrder();
            objs[5] = e.getBusinessNo();
            objs[6] = e.getMaterialsNo();
            objs[7] = e.getMaterialsName();
            objs[8] = e.getUnit();
            objs[9] = e.getPrice();
            objs[10] = e.getInvoiceNum();
            objs[11] = e.getInvoiceAmount();
            objs[12] = e.getRemark();
            dataList.add(objs);
        }
        ExportUtil exportUtil = new ExportUtil(title, rowsName, dataList);
        exportUtil.export(response);

    }

    private void invokeExport(List<ResPurchaseInvoiceList> voList) throws Exception {
        String title = "采购开票数据导出";
        String[] rowsName = new String[]{"序号", "开票申请单号", "供应商代码", "供应商名称", "开票总金额", "已申请付款金额", "状态", "备注", "申请人"
                , "申请日期"};
        List<Object[]> dataList = new ArrayList<Object[]>();
        Object[] objs = null;
        for (int i = 0; i < voList.size(); i++) {
            ResPurchaseInvoiceList e = voList.get(i);
//			takeDecimals(e);
            objs = new Object[rowsName.length];
            objs[0] = i + 1;
            objs[1] = e.getPurchaseInvoiceOrder();
            objs[2] = e.getSupplierOrgid();
            objs[3] = e.getSupplierName();
            objs[4] = e.getInvoicePrice();
            objs[5] = e.getApplyPrice();
            if (e.getStatus() == 0) {
                objs[6] = "待审核";
            } else if (e.getStatus() == 1) {
                objs[6] = "审核通过";
            } else if (e.getStatus() == 2) {
                objs[6] = "审核拒绝";
            } else {
                objs[6] = "";
            }
            objs[7] = e.getRemark();
            objs[8] = e.getApplyName();
            objs[9] = e.getApplyTime();
            dataList.add(objs);

        }
        ExportUtil exportUtil = new ExportUtil(title, rowsName, dataList);
        exportUtil.export(response);
    }

    /**
     * 采购开票时，查询零件价格是否为暂估价
     * 如果不是暂估价，将正式价格同步到采购订单明细中，并更新采购订单总金额
     *
     * @param resInvoiceApplies
     * @param orgId
     * @return
     */
    public Map<String, Object> queryProvisional(List<ResInvoiceApply> resInvoiceApplies, String orgId) {
        Map<String, Object> result = new HashMap<>();
        //保存更新后的价格并返回前端
        Map<String, String> updatePrice = new HashMap<>();
        //判断当前主机厂是否为铲运，如果不是铲运直接返回
        String cyOrgId = companyInfoMapper.getOrgIdBySapCode(CompanyUtil.CY_SAP_CODE);
        if (!StringUtils.equals(cyOrgId, orgId)) {
            result.put("errorCode", ErrorCode.Success);
            return result;
        }
        for (ResInvoiceApply resInvoiceApply : resInvoiceApplies) {
            PurchasePriceDO params = new PurchasePriceDO();
            params.setMaterialsNo(resInvoiceApply.getMaterialNo());
            params.setSupplierOrgId(resInvoiceApply.getSupplierOrgId());
            params.setOrgId(orgId);

            //查询维护的价格是否是暂估价
            List<PurchasePriceDO> purchasePriceDOS = purchasePriceMapper.list(params);
            if (purchasePriceDOS != null) {
                Optional<PurchasePriceDO> purchasePriceDOOptional = purchasePriceDOS.stream()
                        .filter(item -> StringUtils.equals(item.getMaterialsNo(), resInvoiceApply.getMaterialNo()))
                        .findFirst();
                if (purchasePriceDOOptional.isPresent()) {
                    PurchasePriceDO purchasePriceDO = purchasePriceDOOptional.get();
                    Integer provisional = purchasePriceDO.getProvisionalPrice();

                    //不是暂估价，同步正式价格到采购订单行和采购入库单

                    //根据主键查询采购入库单详情
                    PurchaseInboundDetailDO purchaseInboundDetailDO = inboundDetailMapper.selectByPrimaryKey(resInvoiceApply.getId());
                    if (purchaseInboundDetailDO == null) {
                        result.put("errorCode", ErrorCode.Failure);
                        return result;
                    }

                    //是暂估价，继续下次遍历
                    if (provisional == 1) {
                        updatePrice.put(purchaseInboundDetailDO.getId(), null);
                        continue;
                    }

                    BigDecimal purchasePrice = purchasePriceDO.getPrice();
                    BigDecimal inboundDetailPrice = purchasePrice.divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP);
                    PurchaseInboundDetailDO inboundDetailParam = new PurchaseInboundDetailDO();
                    inboundDetailParam.setId(purchaseInboundDetailDO.getId());
                    inboundDetailParam.setPrice(inboundDetailPrice);
                    BigDecimal inboundTotalPrice = inboundDetailPrice.multiply(purchaseInboundDetailDO.getAmount()).setScale(2, BigDecimal.ROUND_HALF_UP);
                    inboundDetailParam.setTotalPrice(inboundTotalPrice);
                    inboundDetailMapper.updateByPrimaryKey(inboundDetailParam);
                    updatePrice.put(purchaseInboundDetailDO.getId(), inboundDetailPrice.toString());
                    //根据采购订单号获取采购订单数据
                    PurchaseRequestDO purchaseRequestDO = purchaseRequestMapper.itemByBillNo(resInvoiceApply.getPurchaseBillNo());
                    //如果采购订单为空，返回失败
                    if (purchaseRequestDO == null) {
                        result.put("errorCode", ErrorCode.Failure);
                        return result;
                    }

                    //如果采购订单明细为空，返回失败
                    PurchaseRequestDetailDO purchaseRequestDetailDO = purchaseRequestDetailMapper.findByBillIdAndMaterialNo(purchaseRequestDO.getBillId(), resInvoiceApply.getMaterialNo(), resInvoiceApply.getRowNo());
                    if (purchaseRequestDetailDO == null) {
                        result.put("errorCode", ErrorCode.Failure);
                        return result;
                    }

                    //更新采购订单明细中的价格
                    PurchaseRequestDetailDO detailDO = new PurchaseRequestDetailDO();
                    detailDO.setBillId(purchaseRequestDO.getBillId());
                    detailDO.setMaterialsNo(resInvoiceApply.getMaterialNo());
                    detailDO.setSettlementPrice(purchasePriceDO.getPrice());
                    BigDecimal requestTotalPrice = purchasePriceDO.getPrice().multiply(purchaseRequestDetailDO.getQty()).setScale(2, BigDecimal.ROUND_HALF_UP);
                    detailDO.setApplyTotalPrice(requestTotalPrice);
                    detailDO.setRowNo(purchaseRequestDetailDO.getRowNo());
                    detailDO.setProvisionalPrice(0);
                    purchaseRequestDetailMapper.update(detailDO);

                    List<PurchaseRequestDetailDO> purchaseRequestDetailDOS = purchaseRequestDetailMapper.list(purchaseRequestDO.getBillId());
                    //计算采购订单明细中的总价格
                    BigDecimal totalPrice = BigDecimal.ZERO;
                    //查询到的明细为空，直接返回失败
                    if (purchaseRequestDetailDOS == null) {
                        result.put("errorCode", ErrorCode.Failure);
                        return result;
                    }
                    for (PurchaseRequestDetailDO requestDetailDO : purchaseRequestDetailDOS) {
                        totalPrice = totalPrice.add(requestDetailDO.getApplyTotalPrice());
                    }
                    //更新采购订单中的总价格
                    PurchaseRequestDO requestDO = new PurchaseRequestDO();
                    requestDO.setBillId(purchaseRequestDO.getBillId());
                    requestDO.setSettlementValue(totalPrice);
                    purchaseRequestMapper.update(requestDO);
                } else {
                    updatePrice.put(resInvoiceApply.getId(), null);
                }
            } else {
                updatePrice.put(resInvoiceApply.getId(), null);
            }
        }

        result.put("errorCode", ErrorCode.Success);
        result.put("value", updatePrice);
        return result;
    }
}
